package com.citybiz.service.interceptor;

import com.alibaba.fastjson2.JSON;
import com.citybiz.common.utils.StringUtils;
import com.citybiz.service.web.service.WxLoginService;
import com.citybiz.system.domain.WxUser;
import com.citybiz.system.domain.WxUserRole;
import com.citybiz.system.service.IWxUserRoleService;
import com.citybiz.system.service.IWxUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.citybiz.service.utils.WxUserAuthUtil;
import com.citybiz.wxcommon.core.domain.model.WxLoginUser;

/**
 * Create by Ykg on 2023/10/3 10:41
 * effect: 微信请求拦截器
 */
@Component
@Slf4j
public class WxAuthInterceptor implements HandlerInterceptor {

    // 令牌标识
    @Value("${token.header}")
    private String header;


    @Autowired
    private WxLoginService wxLoginService;

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private IWxUserRoleService wxUserRoleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(header);
        //拦截器进来先清空threadLocal
        WxUserAuthUtil.rmWxUser();
        if(!preCheck(request) && StringUtils.isEmpty(token)){
            return false;
        }

        WxLoginUser loginUser = wxLoginService.getLoginUser(token);
        if(!preCheck(request) && loginUser == null){
            return false;
        }

        if(loginUser != null) {
            String openId = loginUser.getOpenId();
            WxUser wxUser = wxUserService.getWxUserForOpenId(openId);
            WxUserRole wxUserRole = wxUserRoleService.getWxUserRoleForWxUserId(wxUser.getId(), loginUser.getRole());
            wxUser.setWxUserRole(wxUserRole);
            // 处理器前置处理user
            WxUserAuthUtil.setWxUser(wxUser);
        }
        return true;
    }

    private boolean preCheck(HttpServletRequest request){
        String requestURL = request.getServletPath();
        log.info("request url:{}", requestURL);
        String[] split = requestURL.split("/");
        String suffix = split[split.length - 1];
        String start = split[1];
        return "login".equals(suffix) || "wxIndex".equals(start);
    }
}
